package pers.xiaoliang.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @version v1.0
 * @description: 使用Semaphore信号量 (使用多个许可， 并丢弃部分线程)
 * @author: xiaoliang.liu
 * @date: 2018/7/28 21:31
 */
@Slf4j
public class SemaphoreExample3 {

    private static final int threadCount = 20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 设置允许的并发数(每次最大执行的线程数, 如果设置为1则程序运行则和单线程一样)
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;

            executorService.execute(() -> {
                try {
                    // 尝试获取许可，如果获取不到(只获取上面设置的3个)，则丢弃这个线程
                    if (semaphore.tryAcquire()) {
                        test(threadNum);
                        // 在要控制并发的代码后调用release()方法, 一次释放3个许可
                        semaphore.release();
                    }
                } catch (Exception e) {
                    log.info("{}", e);
                }
            });
        }


        // 等待10毫秒，后继续执行代码
        log.info("finish");
        executorService.shutdown();
    }


    public static void test(int threadNum) throws InterruptedException {
        Thread.sleep(1000);
        log.info("{}", threadNum);
        Thread.sleep(1000);
    }
}
